#!/usr/bin/env bash

PLATFORM=$(uname)
TOOLSPATH="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
CLANGFORMAT="${TOOLSPATH}/${PLATFORM}/clang-format -style=file"

if [ "$1" == "--all" ]
then
    find include src tests/src tools \( -name *.cpp -or -name *.h \) -not -name pugi* -print0 \
    | xargs -n1 -0 ${CLANGFORMAT} -output-replacements-xml \
    | grep -c "<replacement " > /dev/null
    grepCode=$?
elif [ "$1" == "--staged" ]
then
    git diff --cached --name-only --diff-filter=ACMRT | grep -e '.*\.h$' -e '.*\.cpp' -v '**third-party/*' \
    | xargs -n1 ${CLANGFORMAT} -output-replacements-xml \
    | grep -c "<replacement " >/dev/null
    grepCode=$?
else
    echo "Please specify --all or --staged"
    exit 1
fi

# grep exits 0 => found needed formatting changes
if [ $grepCode -ne 0 ]
then
    echo "Formatting looks good!"
    exit 0
else
    echo "****************************************************"
    echo "Code needs formatting!  Please use 'tools/format-all'"
    echo "****************************************************"
    exit 1
fi
